/*验证规则*/
var ui_rule = {
  required: [/[^(^\s*)|(\s*$)]/, '{0}不能为空']
  , int: [/^\d+$/, "请填写数字"]
  , dot: [/^(\-|\+)?\d{1,10}(?:\.\d{0,2})?$/, "请输入数字"]
  , letters: [/^[a-z]+$/i, "请填写字母"]
  , date: [/^\d{4}-\d{2}-\d{2}$/, "请填写有效的日期，格式:yyyy-mm-dd"]
  , time: [/^([01]\d|2[0-3])(:[0-5]\d){1,2}$/, "请填写有效的时间，00:00到23:59之间"]
  , email: [/^[\w\+\-]+(\.[\w\+\-]+)*@[a-z\d\-]+(\.[a-z\d\-]+)*\.([a-z]{2,4})$/i, "请填写有效的邮箱"]
  , url: [/^(https?|s?ftp):\/\/\S+$/i, "请填写有效的网址"]
  , qq: [/^[1-9]\d{4,}$/, "请填写有效的QQ号"]
  , idcard: [/^\d{6}(19|2\d)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)?$/, "请填写正确的身份证号码"]
  , tel: [/^(?:(?:0\d{2,3}[\- ]?[1-9]\d{6,7})|(?:[48]00[\- ]?[1-9]\d{6}))$/, "请填写有效的电话号码"]
  , mobile: [/^1[3-9]\d{9}$/, "请填写有效的手机号"]
  , zipcode: [/^\d{6}$/, "请检查邮政编码格式"]
  , chinese: [/^[\u0391-\uFFE5]+$/, "请填写中文字符"]
  , username: [/^[\u0391-\uFFE5\w\d]{3,12}$/, "请填写3-12位数字、字母、中文、下划线"]
  , password: [/^[\S]{5,16}$/, "请填写5-16位字符，不能包含空格"]
};

layui.use(['jquery', 'form', 'layer', 'upload_hui'], function () {
  var $ = layui.jquery,
    form = layui.form,
    layer = layui.layer,
    upload_hui = layui.upload_hui;

  form.render();
  upload_hui.render();

  //监听页面提交按钮
  $('form.layui-form').on('submit', function (event) {
    if ($(this).hasClass('no-submit')) {
      return true;
    }
    // 获取触发提交的按钮
    var submitButton = $(event.originalEvent.submitter);

    // 检查按钮是否包含 lay-filter="search"
    if (submitButton.attr('lay-filter') === 'search') {
      return true;
    }

    var loading = layer.load(2);
    event.preventDefault();
    // 获取被点击dsubmit的按钮的值
    var submitValue = submitButton.attr('value');
    // 获取表单数据
    var formData = $(this).serialize();
    // 添加submit按钮的值到表单数据中
    if (submitValue) {
      formData += '&submit=' + encodeURIComponent(submitValue);
    }
    $.ajax({
      url: $(this).attr('action'), // 表单的action属性
      method: $(this).attr('method') ?? "post", // 表单的method属性
      data: formData, // 表单数据
      success: function (response) {
        layer.close(loading);
        if (response.code === 1 || response.code === 200) {
          layer.msg(response.msg, {icon: 1, time: 1500}, function () {
            if (response.url) {
              window.location.href = response.url;
            } else {
              window.location.reload();
            }
          })
        } else {
          layer.msg(response.msg, {icon: 2, time: 1500}, function () {
            if (response.url) {
              window.location.href = response.url;
            }
          })
        }
      },
      error: function (xhr, status, error) {
        layer.close(loading);
        // 处理错误
        layer.msg('提交失败，请重试！', {icon: 2});
      }
    });
  });

  // ajax方式请求
  $('.ajaxlink').on("click", function () {
    var url = $(this).attr("href");
    $.ajax({
      type: 'GET',
      url: url,
      dataType: 'json',
      data: {},
      success: function (response, status) {
        layer.msg(response.msg);
        if (response.url !== "") {
          location.href = response.url;
        }
      },
      error: function (xhr, status, error) {
        alert('返回数据异常！');
      }
    });
    return false;
  })

  //监听图片选择弹窗打开
  $('body').on('click', '[data-open-pic]', function () {
    ShowPicList(this);
  });

  //监听图片页面删除功能
  $('.pic_box').on("click", 'dl dd', function () {
    var id = $(this).parents('.pic_box').attr('id');
    var url = $(this).siblings('dt').find('img').data('url');
    var input = $('#' + id);
    var input2 = $('#' + id.replace('_box', ''));
    input2.val('');
    var value = input.val();
    value = value.replace(url, '');
    value = value.replace(/^,/, '');
    value = value.replace(/,$/, '');
    value = value.replace(/,,/, ',');
    input.val(value);
    $(this).parents('dl').remove();
  });


  // 监听弹出层的打开
  $('body').on('click', '[data-open]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-open');
    let reload = parseInt($(this).attr('data-reload'), 10);
    let w = $(this).attr('data-width');
    let h = $(this).attr('data-height');
    HuiAdminShow(title, url, w, h, reload);
  });

  $('body').on('click', '[data-open-full]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-open-full');
    let reload = parseInt($(this).attr('data-reload'), 10);
    HuiAdminOpenFull(title, url, reload);
  });

  $('body').on('click', '[data-confirm]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-confirm');
    let reload = parseInt($(this).attr('data-reload'), 10);
    HuiAdminConfirm(url, title, reload);
  });

  $('body').on('click', '[data-delete]', function () {
    let title = $(this).attr('data-title');
    let url = $(this).attr('data-delete');
    let reload = parseInt($(this).attr('data-reload'), 10);
    let __token__ = $(this).attr('data-token');
    HuiAdminDel(url, title, __token__, reload);
  });

  /* 监听状态设置开关 */
  form.on('switch(switchStatus)', function (data) {
    var that = $(this),
      status = 0;
    if (!that.attr('data-href')) {
      layer.msg('请设置data-href参数');
      return false;
    }
    if (this.checked) {
      status = 1;
    }
    $.post(that.attr('data-href'), {
      val: status,
      no_need__token__: 1
    }, function (res) {
      if (res.code === 1 || res.code === 200) {
        layer.msg(res.msg, {time: 1500, icon: 1}, function () {
          if (res.data.refresh == 1) {
            window.parent.location.reload();
          } else if (res.data.refresh == 2) {
            window.location.reload();
          }
        });
      } else {
        layer.msg(res.msg, {time: 1500, icon: 2}, function () {
          that.trigger('click');
          form.render('checkbox');
        });
      }
    });
  });

  window.HuiAdminShowDrawer = function (title, url, w, h, reload = 0) {
    if (title == null || title == '') {
      title = false;
    }
    if (url == null || url == '') {
      url = "404.html";
    }
    if (w == null || w == '') {
      var window_width = $(window).width();
      if (window_width < 700) {
        w = window_width;
      } else if (window_width >= 700 && window_width < 1200) {
        w = 700;
      } else {
        w = window_width * 0.45;
      }
    }

    parent.layui.drawer.open({
      legacy: false,
      title: [title, 'font-size:16px;color:#2d8cf0'],
      offset: 'r',
      area: w + 'px',
      closeBtn: 1,
      zIndex: parent.layui.layer.zIndex,
      iframe: url,
      end: function () {
        if (reload === 1) {
          window.parent.location.reload();
        } else if (reload === 2) {
          window.location.reload();
        }
        form.render('select');
      }
    })
  }

  /**
   * 弹出层
   * @param title
   * @param url
   * @param w
   * @param h
   * @param reload
   * @param reload_id
   * @constructor
   */
  window.HuiAdminShow = function (title, url, w, h, reload = 0, reload_id = "") {
    if (title == null || title == '') {
      title = false;
    }
    if (url == null || url == '') {
      url = "404.html";
    }
    if (w == null || w == '') {
      w = ($(window).width() * 0.68);
    }
    if (h == null || h == '') {
      h = ($(window).height() * 0.8);
    }
    $.get(url, function (res) {
      if (res.code === 0) {
        hui_msg(res.msg, 2);
        return false;
      }
      parent.layer.open({
        type: 2,
        area: [w + 'px', h + 'px'],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade: 0.4,
        title: title,
        content: url,
        end: function () {
          if (reload === 1) {
            window.parent.location.reload();
          } else if (reload === 2) {
            window.location.reload();
          }
          if (reload_id !== '') {
            layui.table.reload(reload_id);
          }
          form.render('select');
        }
      });
    });
  }

  /*满屏（全屏）打开窗口*/
  window.HuiAdminOpenFull = function (title, url, reload = 0) {
    $.get(url, function (res) {
      if (res.code === 0) {
        Huicmf.events.huiMsg(res.msg, 2);
        return false;
      }
      var index = layer.open({
        type: 2,
        title: title,
        content: url,
        skin: 'skin-layer-hui',
        closeBtn: 11,
        end: function () {
          if (reload === 1) {
            window.parent.location.reload();
          } else if (reload === 2) {
            window.location.reload();
          }
        }
      });
      layer.full(index);
    });
  }

  /**
   * 提示弹出
   * @param url
   * @param msg
   * @param reload
   * @param data
   * @constructor
   */
  window.HuiAdminConfirm = function (url, msg = '真的要这样操作么？', reload = 0, data = {}) {
    layer.confirm(msg, {skin: 'skin-layer-hui'}, function (index) {
      var loading = layer.load(0);
      $.post(url, data, function (res) {
        layer.close(loading);
        if (res.code === 1 || res.code === 200) {
          layer.msg(res.msg, {icon: 1, time: 1500}, function () {
            if (reload === 1) {
              window.parent.location.reload();
            } else if (reload === 2) {
              window.location.reload();
            }
          });
        } else {
          layer.msg(res.msg, {icon: 2});
        }
      })
    });
  }

  /**
   * 删除弹出提示
   * @param url
   * @param msg = '真的要这样操作么？',
   * @param __token__ csrf_token
   * @param reload  1=父级页面刷新，2=当前页面刷新
   * @constructor
   */
  window.HuiAdminDel = function (url, msg = '真的要删除么？', __token__ = "", reload = 0) {
    layer.confirm(msg, {skin: 'skin-layer-hui'}, function (index) {
      var loading = layer.load(0);
      var data = {
        __token__: __token__
      };
      $.post(url, data, function (res) {
        layer.close(loading);
        if (res.code === 1 || res.code === 200) {
          layer.msg(res.msg, {icon: 1, time: 1500}, function () {
            if (reload === 1) {
              parent.location.reload();
            } else if (reload === 2) {
              window.location.reload();
            } else {
              location.reload();
            }
          });
        } else {
          layer.msg(res.msg, {icon: 2});
        }
      });
    });
  };

  /**
   * 图片预览
   * @param id
   * @param src
   */
  window.hui_img_preview = function (id, src) {
    if (src == '') return;
    layer.tips('<img src="' + htmlspecialchars(src) + '" height="100">', '#' + id, {
      tips: [1, '#fff']
    });
  }

  /**
   * 图片选择
   * @param element
   * @constructor
   */
  window.ShowPicList = function (element) {
    var url = $(element).data('open-pic');
    if (!arguments.callee.hWnd || arguments.callee.hWnd.closed) {
      let widowWidth = Math.floor(window.screen.availWidth * 0.8);
      let widowHeight = Math.floor(window.screen.availHeight * 0.7);
      //let windowLeftOld = Math.floor(window.screen.availWidth * 0.1);
      let windowLeft = (window.screenX || window.screenLeft || 0) + (screen.width - widowWidth) / 2;
      let windowTop = Math.floor(window.screen.availHeight * 0.15);
      arguments.callee.hWnd = window.open(url, 'ckeditor', 'titlebar=no, toolbar=no, menubar=no, resizable=no,location=no, status=no,fullscreen=no, width=' + widowWidth + ', height=' + widowHeight + ', left=' + windowLeft + ', top=' + windowTop + '');
    }
    arguments.callee.hWnd.focus();
    window['ckeditor_select_callback'] = function (url, type, input_select_id) {
      if (!url) {
        return false;
      }
      var input = $(element).closest('.huicmf-upload').find('#' + input_select_id)[0];
      var str = "";
      if (type === 'one') {
        $(input).val(url);
        str += '<dl>';
        str += '<dt><img src="' + url + '" data-url="' + url + '"></dt>';
        str += '<dd>删除</dd>';
        str += '</dl>';
        $('#' + input_select_id + '_box').html(str);
      } else {
        var i1 = 0;
        var getItemLength = parseInt($(input).find('.file-item').length);
        var length = GV.site.pic_more_nums;

        $.each(url, function (i, val) {
          let find = $(input).find('.file-item-id-' + val.file_id).html();
          let pidDataName = parent.layui.$("#" + input_select_id).attr('data-name');
          if (pidDataName == '' || pidDataName == null || pidDataName == 'undefined') {
            pidDataName = 'params[thumbs][]';
          }
          if (typeof (find) === 'undefined') {
            i1 += 1;
            str += ' <div class="file-item file-item-id-' + val.file_id + '">\n' +
              '    <img src="' + val.file_path + '">\n' +
              '    <input type="hidden" name="' + pidDataName + '" value="' + val.file_path + '">\n' +
              '    <i class="layui-icon layui-icon-close file-item-delete" onclick="fileItemDelete(' + val.file_id + ')"></i>\n' +
              '</div>';
          }
        })
        var check_length = i1;
        if (length > 1 && length < (check_length + getItemLength)) {
          layer.msg('文件最大同时选择数为：' + length, {
            icon: 2
          });
          return false;
        }
        $(input).append(str);
        $(input).attr('data-nums', (check_length + getItemLength));
      }

    }
  }

  //关闭弹出层
  window.hui_close = function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
  }

  // 删除图片 (数据库已有的)
  window.fileItemDelete = function (id) {
    layer.confirm('您确定要删除该图片吗？', {
      title: '友情提示'
    }, function (index) {
      let picNums = parent.layui.$(".uploader-list").attr('data-nums');
      parent.layui.$(".uploader-list").attr('data-nums', parseInt(picNums) - 1);
      $('.file-item-id-' + id).remove();
      layer.close(index);
    });
  }

  /**
   *
   * @param table 数据
   * @param table_id 表格的id名
   * @param id_attr 要取id的字符串名
   * @returns {boolean|*}
   */
  window.table_get_ids = function (table, table_id, id_attr) {
    var checkStatus = table.checkStatus(table_id)
      , data = checkStatus.data;
    if (data.length < 1) {
      layer.msg('你没有选择任何数据', {icon: 2});
      return false;
    } else {
      var ids = [];
      for (var i = 0; i < data.length; i++) {
        ids += data[i][id_attr] + ',';
      }
      ids = ids.slice(0, -1);
      var arr = ids.split(',');
      for (var i in arr) {
        (arr[i])
      }
      return arr;
    }
  }

  /**
   * 选择图片回调
   * @param url
   * @param type
   * @param input_select_id
   */
  window.send_result_pic = function (url, type, input_select_id = '') {
    if (window.opener && window.opener.ckeditor_select_callback) {
      window.opener.ckeditor_select_callback(url, type, input_select_id);
    } else if (parent.ckeditor_select_callback) {
      parent.ckeditor_select_callback(url, type, input_select_id);
    } else {
      if (type != 'one') {
        url1 = '';
        $(url).each(function (index, res) {
          url1 += res.file_path + ',';
        })
        url1 = url1.substring(0, url1.lastIndexOf(','));
        url = url1;
      }
      copy(url)
      layer.alert('已复制文件地址：<br><span class="en-font">' + url + '</span>');
    }
    window.close();
  }

  window.copy = function (text) {
    var tag = document.createElement('input');
    tag.setAttribute('id', 'copyTextInput');
    tag.value = text;
    document.getElementsByTagName('body')[0].appendChild(tag);
    document.getElementById('copyTextInput').select();
    document.execCommand('copy');
    document.getElementById('copyTextInput').remove();
  }

  window.ajaxData = function (url, type, params, reload = 0, loading = '') {
    $.ajax({
      type: type,
      url: url,
      dataType: "json",
      data: params,
      success: function (response) {
        if (loading) {
          layer.close(loading);
        }
        if (response.code === 200) {
          layer.msg(response.msg, {icon: 1})
        } else {
          layer.msg(response.msg, {icon: 2})
        }
        setTimeout(function () {
          if (reload == 1) {
            location.reload();
          }
        }, 2000)
      },
      error: function () {
        layer.msg('请求失败，请重试！', {icon: 2, time: 1500});
      }
    })
  }

  var Huicmf = {
    events: {
      /**
       * 封装msg消息
       * @param msg
       * @param msg_type 消息类型：1=成功；2=失败；3=.........
       * @param __function 回调函数
       */
      huiMsg: function (msg, msg_type = 1, __function = "") {
        var layer = layui.layer;
        layer.msg(msg, {icon: msg_type, time: 1500}, __function);
      }

    },
    api: {
      ajax: function (options, success, error) {

      },
    }
  }
  //获取数据表格下的多选的id值
  window.table_get_ids = function (obj, table) {
    var id = obj.config.id;
    var checkStatus = table.checkStatus(id);
    if (checkStatus.data.length < 1) {
      layer.msg("请先选择数据", {icon: 2});
      return false;
    }
    var data = checkStatus.data
    var ids = [];
    for (var i = 0; i < data.length; i++) {
      ids += data[i].id + ',';
    }
    ids = ids.slice(0, -1);
    var arr = ids.split(',');
    for (var i in arr) {
      (arr[i])
    }
    return arr;
  }

  window.Huicmf = Huicmf;
  return Huicmf;
});

//html实体转换
function htmlspecialchars(str) {
  str = str.replace(/&/g, '&amp;');
  str = str.replace(/</g, '&lt;');
  str = str.replace(/>/g, '&gt;');
  str = str.replace(/"/g, '&quot;');
  str = str.replace(/'/g, '&#039;');
  return str;
}
